import axios from 'axios'
import router, { resetRoute } from '@/router'
// import store from '@/store'
import store from 'store/index'
import Config from '@/settings'
import NProgress from 'nprogress'
import { requestInterceptors, requestInterceptorsCatch, responseInterceptors, responseInterceptorsCatch } from './interceptors'
import { getPromise, postPromise, exportPromise, uploadPromise, postExportPromise } from './requestPromise'

import type { AxiosInstance, AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios'

import { getSession } from '@/utils/storage'

const baseUrl = process.env.NODE_ENV === 'development' ? Config.requestUrl.dev : Config.requestUrl.pro
// const store = useStore()
const service: AxiosInstance = axios.create({
  baseURL: baseUrl,
  timeout: 30 * 1000, // request timeout 30秒
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  }
})

// 请求前的处理
const requestHook = function (config: AxiosRequestConfig) {
  NProgress.start()
  const token = getSession('token')

  if (token) {
    config.headers.Authorization = token
  }
}
// 请求前的错误处理
const requestCatchHook = function (error: AxiosError) {
  console.log(error, 'requestCatchHook') // for debug
}

// 过期回调
const responseExpireHook = function (response: AxiosResponse) {
  store.dispatch('app/refreshToken')
  // router.push('/login')
  // store.commit('app/SET_TOKEN', '')
  // resetRoute()
  // sessionStorage.clear()
  return response
}

// 响应完成回调
const responseFinishCallback = function (e: any) {
  NProgress.done()
}

// request interceptor
service.interceptors.request.use(requestInterceptors(requestHook), requestInterceptorsCatch(requestCatchHook))

// response interceptor
service.interceptors.response.use(
  responseInterceptors(responseExpireHook, responseFinishCallback),
  responseInterceptorsCatch(responseExpireHook, responseFinishCallback)
)

// 文件上传请求头
export const uploadHeaders: any = {
  // store.app.token
  [Config.TokenKey]: getSession('token')
}

export const get = (url: string, params?: any) => getPromise(service, url, params) // get 请求
export const post = (url: string, params?: any) => postPromise(service, url, params) // post 请求
export const exportExcel = (url: string, params: any) => exportPromise(service, url, params) // 导出
export const upload = (url: string, files: Blob, config?: AxiosRequestConfig) => uploadPromise(service, url, files, config) // 上传
export const postExcel = (url: string, paramss: any) => postExportPromise(service, url, paramss)

export function downloadFileProgress(url: string, data: object, config: object): object {
  return service({
    method: 'get',
    url: url,
    data: data,
    ...config,
    responseType: 'blob'
  })
}

export default service
